import {Component, OnInit} from '@angular/core';
import {FormGroup, FormBuilder, Validators, FormControl} from '@angular/forms';
import {RegisterTransferService} from './register-transfer.service';
import {HttpClient} from '@angular/common/http';
import {AppUrl} from '../../../app.url';

@Component({
    selector: 'app-step2',
    template: `
        <form nz-form [formGroup]="form" (ngSubmit)="_submitForm()">
            <div nz-form-item nz-row>
                <div nz-form-label nz-col [nzSm]="4">
                    <label for="username" nz-form-item-required>用户名</label>
                </div>
                <div nz-form-control nz-col [nzSm]="20" nzHasFeedback>
                    <nz-input formControlName="username" nzSize="large" [nzId]="'username'"></nz-input>
                    <ng-container *ngIf="username.dirty || username.touched">
                        <p nz-form-explain *ngIf="username.errors?.required">请输入用户名</p>
                    </ng-container>
                </div>
            </div>
            <div nz-form-item nz-row>
                <div nz-form-label nz-col [nzSm]="4">
                    <label for="password" nz-form-item-required>密码</label>
                </div>
                <div nz-form-control nz-col [nzSm]="20" nzHasFeedback [nzValidateStatus]="password">
                    <nz-input formControlName="password" nzSize="large" [nzId]="'password'"></nz-input>
                    <ng-container *ngIf="password.dirty || password.touched">
                        <p nz-form-explain *ngIf="password.errors?.required">请输入密码</p>
                    </ng-container>
                </div>
            </div>
            <div nz-form-item nz-row>
                <div nz-form-label nz-col [nzSm]="4">
                    <label for="conform" nz-form-item-required>确认密码</label>
                </div>
                <div nz-form-control nz-col [nzSm]="20" nzHasFeedback [nzValidateStatus]="confirm">
                    <nz-input formControlName="confirm" nzSize="large" [nzId]="'conform'"></nz-input>
                    <ng-container *ngIf="confirm.dirty || confirm.touched">
                        <p nz-form-explain *ngIf="confirm.errors?.required">请确认密码！</p>
                        <p nz-form-explain *ngIf="confirm.errors?.equar">两次输入的密码不匹配！</p>
                    </ng-container>
                </div>
            </div>
            <div nz-form-item nz-row>
                <div nz-form-label nz-col [nzSm]="4">
                    <label for="roletype">选择身份</label>
                </div>
                <div nz-form-control nz-col [nzSm]="20">
                    <nz-radio-group formControlName="roletype" [(ngModel)]="roletypeValue">
                        <label nz-radio [nzValue]="'B'">
                            <span>企业</span>
                        </label>
                        <label nz-radio [nzValue]="'S'">
                            <span>学生</span>
                        </label>
                    </nz-radio-group>
                </div>
            </div>

            <div nz-form-item nz-row>
                <div nz-form-control nz-col [nzSm]="20">
                    <a routerLink="" style="margin-left: 2px;color:dimgray;font-size: 1.2vh">--辛易校园注册协议--</a>
                </div>
            </div>

            <div nz-form-item nz-row>
                <div nz-form-control nz-col [nzSpan]="20" [nzOffset]="4">
                    <button nz-button [nzType]="'primary'" nzSize="large" [nzLoading]="loading"
                            [disabled]="form.invalid">同意协议并注册
                    </button>
                    <button nz-button (click)="prev()" nzSize="large">上一步</button>
                </div>
            </div>
        </form>
        <div class="alert" id="alert" style=" display: none; sition: absolute; top: 10%; z-index: 1000;">
            <nz-alert [nzType]="'error'" [nzMessage]="'Error'" [nzCloseable]="'false'"
                      [nzDescription]="'用户已存在.'" [nzShowIcon]="'true'"></nz-alert>
        </div>
        <div class="alert" id="salert" style=" display: none; sition: absolute; top: 10%; z-index: 1000;">
            <nz-alert [nzType]="'error'" [nzMessage]="'Error'" [nzCloseable]="'false'"
                      [nzDescription]="'服务错误.'" [nzShowIcon]="'true'"></nz-alert>
        </div>
    `
})
export class RegisterStep2Component implements OnInit {
    form: FormGroup;
    loading = false;
    roletypeValue = 'B';

    constructor(private fb: FormBuilder, public item: RegisterTransferService, private http: HttpClient) {
    }

    ngOnInit() {
        this.form = this.fb.group({
            username: [null, [Validators.required, Validators.minLength(4), Validators.maxLength(50)]],
            password: [null, [Validators.required, Validators.minLength(6), Validators.maxLength(50), RegisterStep2Component.checkPassword.bind(this)]],
            confirm: [null, [Validators.required, Validators.minLength(6),, Validators.maxLength(50), RegisterStep2Component.passwordEquar]],
            roletype: [null, [Validators.required]],
        });
        this.form.patchValue(this.item);
        console.log(this.form);
    }

    static checkPassword(control: FormControl) {
        if (!control) return null;
        const self: any = this;
        self.visible = !!control.value;
        if (control.value && control.value.length > 9)
            self.status = 'ok';
        else if (control.value && control.value.length > 5)
            self.status = 'pass';
        else
            self.status = 'pool';

        if (self.visible) self.progress = control.value.length * 10 > 100 ? 100 : control.value.length * 10;
    }

    static passwordEquar(control: FormControl) {
        if (!control || !control.parent) return null;
        if (control.value !== control.parent.get('password').value) {
            return {equar: true};
        }
        return null;
    }

    //#region get form fields
    get username() {
        return this.form.controls['username'];
    }

    get password() {
        return this.form.controls['password'];
    }

    get confirm() {
        return this.form.controls['confirm'];
    }

    get roletype() {
        return this.form.controls['roletype'];
    }

    //#endregion

    _submitForm() {
        this.loading = true;

        this.http.post(AppUrl.sign.signUp, {username:  this.username.value, password: this.password.value, phoneNum:  this.item.mobile, roletype: this.roletype.value})
            .subscribe(data => {
                this.loading = false;
                let temp: any;
                temp = data;
                if (temp.code === 200) {
                    // 注册成功
                    ++this.item.step;
                    localStorage.setItem('username', this.username.value);
                } else if (temp.code === 400) {
                    // 用户已存在
                    document.getElementById('alert').style.display = 'block';
                    setTimeout(() => {
                        document.getElementById('alert').style.display = 'none';
                    }, 3000);
                } else if (temp.status) {
                    // 服务错误
                    document.getElementById('salert').style.display = 'block';
                    setTimeout(() => {
                        document.getElementById('salert').style.display = 'none';
                    }, 3000);
                }
            });
    }

    prev() {
        --this.item.step;
    }
}
